package leetcode.code0335;

public class Solution extends Solution335 {

	private int len;

	@Override
	public boolean isSelfCrossing(int[] distance) {
		this.len = distance.length;
		if (len < 4)// 不足4个撞不上
			return false;
		int index = 3;
		if (index < len) {
			int[] line4 = this.lineCur(distance, index);
			int[] line1 = new int[] { 0, distance[0], 0, 0 };
			boolean b = this.chuizhi(line4, line1);
			if (b)
				return true;
		}
		return false;//
	}

	private int[] lineCur(int[] d, int cur) {
		if ((cur & 1) == 0) {
			return new int[] { d[cur - 1], d[cur], d[cur - 1], d[cur - 2] };
		} else {
			return new int[] { d[cur], d[cur - 1], d[cur - 2], d[cur - 1] };
		}
	}

	private boolean shuiping(int[] line1, int[] line2) {// 两条互相垂直的线是否相交
		if (line1[1] == line1[3]) { // line1 是水平的
			return this.x(line1, line2);
		} else {
			return this.y(line2, line1); // line1是垂直
		}
	}

	private boolean x(int[] line1, int[] line2) {
		int x1 = line1[0] < line1[2] ? line1[0] : line1[2];
		int x3 = line1[0] < line1[2] ? line1[2] : line1[0];
		int x2 = line2[0] < line2[2] ? line2[0] : line2[2];
		int x4 = line2[0] < line2[2] ? line2[2] : line2[0];
		if (Math.max(x1, x2) <= Math.min(x3, x4)) {
			return true;
		}
		return false;
	}

	private boolean y(int[] line2, int[] line1) {
		int y1 = line1[1] < line1[3] ? line1[1] : line1[3];
		int y3 = line1[1] < line1[3] ? line1[3] : line1[1];
		int y2 = line2[1] < line2[3] ? line2[1] : line2[3];
		int y4 = line2[1] < line2[3] ? line2[3] : line2[1];
		if (Math.max(y1, y2) <= Math.min(y3, y4)) {
			return true;
		}
		return false;
	}

	private boolean chuizhi(int[] line1, int[] line2) {// 两条互相垂直的线是否相交
		if (line1[1] == line1[3]) { // line1 是水平的
			return this.chui(line1, line2);
		} else {
			return this.chui(line2, line1); // line2是水平的
		}
	}

	private boolean chui(int[] line1, int[] line2) {
		int x1 = line1[0];
		int y1 = line1[1];
		int x3 = line1[2];
//		int y3 = line1[3]; // == y1
		int x2 = line2[0];
		int y2 = line2[1];
//		int x4 = line2[2]; // == x2
		int y4 = line2[3];
		boolean b1 = false;
		if ((x1 < x3 && x1 <= x2 && x2 <= x3) || (x3 <= x2 && x2 <= x1)) {
			b1 = true;
		}
		boolean b2 = false;
		if ((y2 < y4 && y2 <= y1 && y1 <= y4) || (y4 <= y1 && y1 <= y2)) {
			b2 = true;
		}
		return b1 && b2;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
//		so.debug2();
//		so.debug3();
//		so.debug4();
//		so.debug5();
//		so.debug6();
//		so.debug7();
//		so.debug8();
	}

}
